#!/usr/bin/env python
# -*- coding:utf-8 -*-
from typing import List

from conn.MyLogs import MyLogs
from excel.LFREE.LfreeObj import LfreeObj


# ***
# * 这个工具类主要处理数据表中针对dataL!这个固定标准表数据的读取与判断
# * Auth: tuut
# ***
class LfreeDictUtil:
    SUCCESS = 200
    LOST_DATA = 400
    SYSTEM_ERROR = 500

    def __init__(self, conn):
        self.conn = conn
        return

    @staticmethod
    def make_json_key(select_payment, select_anb, sum_assured, gender, smoker, repeat_plan, repeat_growth_rate,
                      currency, promotion, withdrawal_starting_anb, surrender_anb, withdrawal_years, inflation,
                      fst_year_withdrawal, ):
        keys = [str(select_payment), str(select_anb), str(sum_assured), str(gender), str(smoker),
                str(repeat_plan), str(repeat_growth_rate), str(currency), str(promotion),
                str(withdrawal_starting_anb), str(surrender_anb), str(withdrawal_years), str(inflation),
                str(fst_year_withdrawal)]
        return '-'.join(keys)

    @staticmethod
    def get_json_key(json_key):
        return json_key.split("-")

    # **
    # 年期 单一计算单元年数
    # 供款期 判定基础数据来源
    def vlookup_by_year_and_anb_and_payment_term(self, args: List[str]):
        year = args[0]
        anb = args[1]
        payment_term = args[2]
        cal_anb_index = args[3]
        if year == 0:
            return {"code": LfreeDictUtil.SUCCESS, "data": 0}
        # cal_anb_index = LfreeDictUtil.get_anb_index(anb)
        # 根据 供款期 选择对应的数据表
        area_table = LfreeObj.PAYMENT_TERM[payment_term]
        try:
            # 1 数据查询 -----------------------------------------------------------------------------------
            fetch_sql = f"SELECT val FROM {area_table} %s"
            where_sql = f' WHERE 1=1'
            where_sql = where_sql + f' AND anb_index = {cal_anb_index}'
            where_sql = where_sql + f' AND year = {year}'
            data_list = self.conn.sql_fetch(fetch_sql % where_sql)
            if len(data_list) > 0:
                # return {"code": 200, "data": list([i[0] for i in data_list])} 从队列数据 转变直接获取数据，取消多年份数据
                return {"code": LfreeDictUtil.SUCCESS, "data": data_list[0][0]}
            return {"code": LfreeDictUtil.LOST_DATA, "data": None}
        except Exception as e:
            MyLogs.logger.error("ERROR: %s" % e)
        return {"code": LfreeDictUtil.SYSTEM_ERROR, "data": None}

    # **
    # 年期 单一计算单元年数
    # 供款期 判定基础数据来源
    def vlookup_gcv_by_year_and_anb_and_payment_term(self, args: List[str]):
        year = args[0]
        anb = args[1]
        payment_term = args[2]
        cal_anb_index = args[3]
        if year == 0:
            return {"code": LfreeDictUtil.SUCCESS, "data": 0}
        # cal_anb_index = LfreeDictUtil.get_anb_index(anb)  # 通过翌年歲下标确认使用利率范围
        area_table = LfreeObj.GCV_PAYMENT_TERM[payment_term]  # 通过供款期确定使用数据表
        try:
            # 1 数据查询 -----------------------------------------------------------------------------------
            fetch_sql = f"SELECT val FROM {area_table} %s"
            where_sql = f' WHERE 1=1'
            where_sql = where_sql + f' AND anb_index = {cal_anb_index}'
            where_sql = where_sql + f' AND year = {year}'  # 计算年期
            data_list = self.conn.sql_fetch(fetch_sql % where_sql)
            if len(data_list) > 0:
                # return {"code": 200, "data": list([i[0] for i in data_list])} 从队列数据 转变直接获取数据，取消多年份数据
                return {"code": LfreeDictUtil.SUCCESS, "data": data_list[0][0]}
            return {"code": LfreeDictUtil.LOST_DATA, "data": None}
        except Exception as e:
            MyLogs.logger.error("ERROR: %s" % e)
        return {"code": LfreeDictUtil.SYSTEM_ERROR, "data": None}

    # **
    # 年期 单一计算单元年数
    # 供款期 判定基础数据来源
    def vlookup_fmns_by_anb(self, args: List[str]):
        area_table = args[0]
        cal_anb_index = args[1]
        anb = args[2]
        if anb == 0:
            return {"code": LfreeDictUtil.SUCCESS, "data": 0}
        try:
            # 1 数据查询 -----------------------------------------------------------------------------------
            fetch_sql = f"SELECT val FROM {area_table} %s"
            where_sql = f' WHERE 1=1'
            where_sql = where_sql + f' AND anb_index = {cal_anb_index}'
            where_sql = where_sql + f' AND anb = {anb}'  # 计算年期
            data_list = self.conn.sql_fetch(fetch_sql % where_sql)
            if len(data_list) > 0:
                # return {"code": 200, "data": list([i[0] for i in data_list])} 从队列数据 转变直接获取数据，取消多年份数据
                return {"code": LfreeDictUtil.SUCCESS, "data": data_list[0][0]}
            return {"code": LfreeDictUtil.LOST_DATA, "data": None}
        except Exception as e:
            MyLogs.logger.error("ERROR: %s" % e)
        return {"code": LfreeDictUtil.SYSTEM_ERROR, "data": None}

    @staticmethod
    def spow(n, m):
        res = 1
        for i in range(m):
            res *= n
        return res

    def insert_cal_json_data(self, args: List[str]) -> None:
        hkey = args[0]
        val_json = args[1]
        sys_time = args[2]
        try:
            fetch_sql = f"SELECT COUNT(1) FROM CAL_RAW_DATA WHERE `hkey` = \'{hkey}\'"
            check = self.conn.sql_fetch(fetch_sql)
            if check[0][0] > 0:
                return
            execute_sql = f" INSERT INTO CAL_RAW_DATA (hkey,val_json,sys_time) VALUES (\'%s\',\'%s\',\'%s\') "
            execute_sql = execute_sql % (hkey, val_json, sys_time)
            self.conn.sql_execute(execute_sql)
        except Exception as e:
            print(e)

    def get_cal_anb_index(self, anb):
        try:
            fetch_sql = f"SELECT MAX(idx) as idx FROM CAL_ANB_INDEX WHERE idx<= {anb}"
            check = self.conn.sql_fetch(fetch_sql)
            if len(check[0]) > 0:
                return check[0][0]
            return 0
        except Exception as e:
            print(e)
